<template>
	<s-layout title="购物车" tabbar="/pages/index/cart" :bgStyle="{ color: '#fff' }">
		<s-empty v-if="state.list.length === 0" text="购物车空空如也,快去逛逛吧~" icon="/static/cart-empty.png" />

		<!-- 头部 -->
		<view class="cart-box ss-flex ss-flex-col ss-row-between" v-if="state.list.length">
			<view class="cart-header ss-flex ss-col-center ss-row-between ss-p-x-30">
				<view class="header-left ss-flex ss-col-center ss-font-26">
					共
					<text class="goods-number ui-TC-Main ss-flex">
						{{ state.list.length }}
					</text>
					款商品
				</view>
				<view class="header-right">
					<button v-if="state.editMode" class="ss-reset-button" @tap="onChangeEditMode(false)">
						取消
					</button>
					<button v-else class="ss-reset-button ui-TC-Main" @tap="onChangeEditMode(true)">
						编辑
					</button>
				</view>
			</view>
			<!-- 内容 -->
			<view class="cart-content ss-flex-1 ss-p-x-30 ss-m-b-40 ss-m-t-30">
				<!-- 滑块删除组件 -->
				<uv-swipe-action v-for="item in state.list" :key="item.id">
					<uv-swipe-action-item 
						:options="getSwipeOptions(item)" 
						@click="handleSwipeAction($event, item)"
					>
						<view class="goods-box ss-r-10 ss-m-b-8">
							<view class="goods-container">
								<!-- 左侧单选框 -->
								<label class="check-box" @tap="onSelectSingle(item.id)">
									<radio :checked="state.selectedIds.includes(item.id)" color="var(--ui-BG-Main)"
										style="transform: scale(0.8)" @tap.stop="onSelectSingle(item.id)" />
								</label>

								<!-- 中间商品信息 -->
								<view class="goods-main">
									<!-- 商品基本信息 -->
									<view class="goods-info">
										<s-goods-item
											:title="item.goods?.title || ''"
											:img="item.sku_price?.image || item.goods?.image || ''"
											:skuText="item.sku_price?.goods_sku_text || item.goods?.subtitle || ''"
											:price="userInfo && userInfo.level >= 1 ? (item?.goods?.vip_price || item?.sku_price?.vip_price || (Array.isArray(item?.goods?.price) ? item?.goods?.price[0] : item?.goods?.price) || (Array.isArray(item?.sku_price?.price) ? item?.sku_price?.price[0] : item?.sku_price?.price) || '') : ((Array.isArray(item?.goods?.price) ? item?.goods?.price[0] : item?.goods?.price) || (Array.isArray(item?.sku_price?.price) ? item?.sku_price?.price[0] : item?.sku_price?.price) || '')"
											:originalPrice="getOriginalPrice(item, userInfo)"
											:microbean="item.microbean || item.sku_price?.microbean || item.goods?.microbean || ''"
											priceColor="#FF7C00"
											:titleWidth="380"
											@click="goToGoodsDetail(item.goods?.id)">
											<!-- 自定义加减框 -->
											<template v-slot:priceSuffix>
												<view v-if="!state.editMode" class="number-box-inline">
													<su-number-box :min="1" :max="item.sku_price?.stock || 999" :step="1"
														v-model="item.goods_num" @change="onNumberChange($event, item)"
														@click.stop @tap.stop></su-number-box>
												</view>
											</template>
										</s-goods-item>
									</view>
								</view>


							</view>

							<!-- 下架遮罩 -->
							<view v-if="item.status === 'down' && !state.editMode" class="down-box">
								该商品已下架
							</view>
						</view>
					</uv-swipe-action-item>
				</uv-swipe-action>
			</view>
			<!-- 底部 -->
			<su-fixed bottom :val="0" v-if="state.list.length > 0" :isInset="false">
				<view class="cart-footer ss-flex ss-col-center ss-row-between ss-p-x-20 ss-p-y-12 border-bottom">
					<view class="footer-left ss-flex ss-col-center">
						<label class="check-box ss-flex ss-col-center ss-p-r-16" @tap="onSelectAll">
							<radio :checked="state.isAllSelected" color="var(--ui-BG-Main)"
								style="transform: scale(0.8)" @tap.stop="onSelectAll" />
							<view class="all-text"> 全选 </view>
						</label>
						<view class="price-info ss-flex-col">
							<view class="total-price">
								<text>合计：</text>
								<view class="text-price price-text">
									{{ state.totalPriceSelected }}
								</view>
							</view>
							<!-- 微豆奖励显示 -->
							<view v-if="getTotalMicrobean() > 0" class="microbean-reward">
								<text class="reward-text">奖励</text>
								<image mode="widthFix" :src="'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/goldenBean.png'" class="goldenBean-img"></image>
								<text class="microbean-count">{{ getTotalMicrobean() }}</text>
								<text class="reward-text">微豆</text>
							</view>
						</view>
					</view>
					<view class="footer-right">
						<view v-if="state.editMode" class="pay-btn" @tap="onDelete">
							删除
						</view>
						<view v-else class="pay-btn" @tap="onConfirm">
							去结算
							{{ state.selectedIds?.length ? `(${state.selectedIds.length})` : '' }}
						</view>
					</view>
				</view>
			</su-fixed>
		</view>
	</s-layout>
</template>

<script setup>
	import sheep from '@/sheep';
	import { computed, reactive, unref } from 'vue';
	import { onShow } from '@dcloudio/uni-app';
	import UvSwipeAction from '@/uni_modules/uv-swipe-action/components/uv-swipe-action/uv-swipe-action.vue';
	import UvSwipeActionItem from '@/uni_modules/uv-swipe-action/components/uv-swipe-action-item/uv-swipe-action-item.vue';

	const sys_navBar = sheep.$platform.navbar;
	const cart = sheep.$store('cart');

	// 获取用户信息
	const userInfo = () => sheep.$store('user').userInfo;

	const state = reactive({
		editMode: computed(() => cart.editMode),
		list: computed(() => cart.list),
		selectedList: [],
		selectedIds: computed(() => cart.selectedIds),
		isAllSelected: computed(() => cart.isAllSelected),
		totalPriceSelected: computed(() => cart.totalPriceSelected),
	});





	// 跳转到商品详情页
	const goToGoodsDetail = (goodsId) => {
		uni.navigateTo({
			url: `/subPackages/goods/index?id=${goodsId}`
		});
	};

	// 单选选中
  function onSelectSingle(id) {
    cart.selectSingle(id);
  }

	// 编辑、取消
	function onChangeEditMode(flag) {
		cart.onChangeEditMode(flag);
	}

	// 全选
	function onSelectAll() {
		cart.selectAll(!state.isAllSelected);
	}

	// 结算
	function onConfirm() {
		let goods_list = [];
		state.selectedList = state.list.filter((item) => state.selectedIds.includes(item.id));
		state.selectedList.map((item) => {
			goods_list.push({
				goods_id: item.goods_id,
				goods_num: item.goods_num,
				goods_sku_price_id: item.goods_sku_price_id,
			});
		});
		if (goods_list.length === 0) {
			sheep.$helper.toast('请选择商品');
			return;
		}
		sheep.$router.go('/subPackages/order/confirm', {
			data: JSON.stringify({
				order_type: 'goods',
				goods_list,
				from: 'cart',
			}),
		});
	}

	function onNumberChange(e, cartItem) {
		if (e === 0) {
			cart.delete(cartItem.id);
			return;
		}
		if (cartItem.goods_num === e) return;
		cartItem.goods_num = e;
		cart.update({
			goods_id: cartItem.goods_id,
			goods_num: e,
			goods_sku_price_id: cartItem.goods_sku_price_id,
		});
	}

	function onDelete() {
		// 检查是否选择了要删除的商品
		if (!state.selectedIds || state.selectedIds.length === 0) {
			sheep.$helper.toast('请选择删除的商品');
			return;
		}

		// 显示删除确认对话框
		const itemCount = state.selectedIds.length;
		uni.showModal({
			title: '温馨提示',
			content: `你确认要将选中的${itemCount}个商品删除吗？`,
			confirmText: '确认删除',
			cancelText: '取消',
			confirmColor: '#FF7C00', // 确认按钮颜色与价格颜色一致
			success: (res) => {
				if (res.confirm) {
					// 用户确认删除，删除选中的商品
					cart.delete(state.selectedIds);
				}
			}
		});
	}

	function getCartList() {
		cart.getList();
	}

	// 获取划线价格 - 与主页面的逻辑保持一致
	function getOriginalPrice(item, userInfo) {
		// 只有VIP用户且同时存在vip_price和original_price才显示划线价格
		if (!userInfo || userInfo.level === 0) {
			return '';
		}

		// 检查是否存在VIP价格
		const vipPrice = item?.goods?.vip_price || item?.sku_price?.vip_price;
		if (!vipPrice) {
			return '';
		}

		// 辅助函数：获取价格值，处理数组格式
		const getPriceValue = (price) => {
			if (Array.isArray(price)) {
				return price[0] || '';
			}
			return price || '';
		};

		// 优先使用 original_price
		const originalPrice = item?.goods?.original_price || item?.sku_price?.original_price;
		if (originalPrice) {
			return getPriceValue(originalPrice);
		}

		// 如果没有 original_price，使用 price 作为备用
		const price = item?.goods?.price || item?.sku_price?.price;
		if (price) {
			return getPriceValue(price);
		}

		return '';
	}

	// 计算总微豆奖励
	function getTotalMicrobean() {
		let total = 0;
		if (!state.selectedIds.length) return total;

		state.list.forEach((item) => {
			if (state.selectedIds.includes(item.id)) {
				const microbean = item.microbean || item.sku_price?.microbean || item.goods?.microbean || 0;
				total += Number(microbean) * item.goods_num;
			}
		});

		return total;
	}
	// 显示原生tabBar
	uni.showTabBar({
		fail: () => {},
	});

	// 获取滑块选项
	function getSwipeOptions(item) {
		return [
			{
				text: '删除',
				style: {
					backgroundColor: '#FF7C00',
					color: '#ffffff',
					fontSize: '28rpx'
				}
			}
		];
	}

	// 处理滑块操作
	function handleSwipeAction(e, item) {
		// e.index 是按钮的索引
		if (e.index === 0) {
			// 获取商品标题
			const goodsTitle = item.goods?.title || '';
			// 显示删除确认对话框
			uni.showModal({
				title: '温馨提示',
				content: `确认删除${goodsTitle}这个商品吗？`,
				confirmText: '确认删除',
				cancelText: '取消',
				confirmColor: '#FF7C00',
				success: (res) => {
					if (res.confirm) {
						// 用户确认删除，删除单个商品
						cart.delete(item.id);
					}
				}
			});
		}
	}

	onShow(() => {
		getCartList();
	});
</script>

<script>
// 组件注册
export default {
	components: {
		UvSwipeAction,
		UvSwipeActionItem
	}
}
</script>

<style lang="scss" scoped>
	:deep(.ui-fixed) {
		height: 72rpx;
	}

	.pay-btn {
		width: 200rpx;
		height: 80rpx;
		background: #FF7C00;
		line-height: 80rpx;
		text-align: center;
		border-radius: 5rpx;
		font-family: PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #FFFFFF;
	}

	.cart-box {
		width: 100%;

		.cart-header {
			height: 70rpx;
			background-color: #fff;
			width: 100%;
			position: fixed;
			left: 0;
			top: v-bind('sys_navBar') rpx;
			z-index: 1000;
			box-sizing: border-box;
		}

		.cart-footer {
			min-height: 110rpx;
			background-color: #fff;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 999;
			box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);
			// border-top: 1rpx solid #f0f0f0;

			.all-text {
				font-family: PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #2B303C;
			}

		}

		.cart-content {
			margin-top: 70rpx;
			margin-bottom: 110rpx; // 为底部按钮留出空间
			padding: 0 16rpx;

			.goods-box {
				background-color: #fff;
				position: relative;
				border-radius: 10rpx;
				padding: 12rpx;
			}

			// 下架商品
			.down-box {
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				background: rgba(#fff, 0.8);
				z-index: 2;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #999;
				font-size: 32rpx;
			}

			.goods-container {
				display: flex;
				align-items: center;
				padding: 0;
				position: relative;

				.check-box {
					padding: 0 4rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					min-width: 32rpx;
				}

				.goods-main {
					flex: 1;
					position: relative;

					.goods-info {
						width: 100%;
					}
				}

			}
		}


		.price-info {
			display: flex;
			flex-direction: column;
			gap: 4rpx;
			margin-left: 12rpx;

			.total-price {
				display: flex;
				align-items: center;
				gap: 8rpx;

				text {
					font-size: 22rpx;
					color: #333;
					font-weight: 400;
				}

				.price-text {
					font-size: 24rpx;
					font-weight: 500;
					color: #FF7C00;
				}
			}

		}


		.custom-price {
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			gap: 4rpx;
			margin-top: 8rpx;

			.vip-price {
				font-size: 28rpx;
				font-weight: 600;
				color: #FF7C00;
				line-height: 1.2;
			}

			.original-price {
				font-size: 22rpx;
				font-weight: 400;
				color: #999;
				line-height: 1.2;
				text-decoration: line-through;
				text-decoration-color: #999;
				text-decoration-thickness: 1rpx;
			}

			.normal-price {
				font-size: 28rpx;
				font-weight: 600;
				color: #FF7C00;
				line-height: 1.2;
			}
		}
	}

		.price-with-number {
			display: flex;
			align-items: center;
			gap: 12rpx;

			.price-container {
				display: flex;
				flex-direction: row;
				align-items: center;
				gap: 8rpx;
				justify-content: flex-start;

				.current-price {
					font-size: 28rpx;
					font-weight: 600;
					color: #FF7C00;
					line-height: 1.2;
				}

				.original-price-colored {
					font-size: 24rpx;
					font-weight: 400;
					color: #999;
					line-height: 1.2;
					text-decoration: line-through;
					text-decoration-color: #999;
					text-decoration-thickness: 1rpx;
				}
			}

			.number-box-inline {
				display: flex;
				align-items: center;
				margin-left: 12rpx;
			}
		}

		.microbean-reward {
			display: flex;
			align-items: center;
			gap: 2rpx;
			margin-top: 6rpx;

			.goldenBean-img {
				width: 20rpx;
				height: 20rpx;
			}

			.reward-text {
				font-size: 20rpx;
				font-weight: 400;
				color: #FF7C00;
				line-height: 1.2;
			}

			.microbean-count {
				font-size: 20rpx;
				font-weight: 500;
				color: #FF7C00;
				line-height: 1.2;
				margin: 0 2rpx;
			}
		}

	// 滑块相关样式
	:deep(.uv-swipe-action-item) {
		margin-bottom: 8rpx;
	}

	:deep(.uv-swipe-action-item__content) {
		background-color: transparent;
	}

	:deep(.uv-swipe-action-item__right__button__wrapper) {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	// 确保商品项支持触摸操作
	.goods-box {
		background-color: #fff;
		border-radius: 10rpx;
	}
</style>